package com.dianrui.operation.okhttp;

import android.os.Handler;
import android.os.Looper;

import com.blankj.utilcode.util.LogUtils;
import com.dianrui.operation.util.SharedUtil;
import com.dianrui.operation.util.StringUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.CallBack;
import com.xuexiang.xhttp2.exception.ApiException;

import org.json.JSONException;

import okhttp3.OkHttpClient;

public class XHttpRequest {
    private Handler handler;
    private volatile static XHttpRequest mInstance;
    private OkHttpClient mOkHttpClient;

    public XHttpRequest(OkHttpClient okHttpClient) {
        handler = new Handler(Looper.getMainLooper());
        if (okHttpClient == null) {
            mOkHttpClient = new OkHttpClient();
        } else {
            mOkHttpClient = okHttpClient;
        }
    }


    /**
     * 单例模式
     */
    //获取单利
    public static XHttpRequest getInstance() {

        return initClient(null);

    }

    public static XHttpRequest initClient(OkHttpClient okHttpClient) {
        if (mInstance == null) {
            synchronized (XHttpRequest.class) {
                if (mInstance == null) {
                    mInstance = new XHttpRequest(okHttpClient);
                }
            }
        }
        return mInstance;
    }


    public void postRequests(final String url, final String requestparams, final XCallBack callback) {
        String token = SharedUtil.getToken();
        LogUtils.e("当前token是:--->"+token);
        XHttp.post(url).upJson(requestparams).keepJson(true).headers("token", token).execute(new CallBack<String>() {

            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(String response) {
                if (!StringUtils.isEmpty(response)) {
                    onSuccessResponse(response, callback);
                    LogUtils.e("服务器返回数据>============================================网络请求[" + "],请求日志如下===================================" +
                            "\n\n传给服务器地址:" + url +
                            "\n\n传给服务器的参数:" + requestparams +
                            "\n\n服务器返回的数据>" + response);
                }else {
                    onFailedResponse(response, callback);
                }
            }

            @Override
            public void onError(ApiException e) {
                LogUtils.e("请求失败=" + e.getMessage());
                onFailedResponse(e.toString(), callback);
            }

            @Override
            public void onCompleted() {

            }
        });
    }

    public void postRequest(final String url, final String requestparams, final XCallBack callback) {
        XHttp.post(url).upJson(requestparams).keepJson(true).execute(new CallBack<String>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(String response) throws Throwable {
                if (!StringUtils.isEmpty(response)) {
                    onSuccessResponse(response, callback);
                    LogUtils.e("服务器返回数据>============================================网络请求[" + "],请求日志如下===================================" +
                            "\n\n传给服务器地址:" + url +
                            "\n\n传给服务器的参数:" + requestparams +
                            "\n\n服务器返回的数据>" + response);
                }else {
                    LogUtils.e("服务器返回数据>===========================================网络请求[" + "],请求日志如下===================================" +
                            "\n\n传给服务器地址:" + url +
                            "\n\n服务器返回的数据>" + response);
                    onFailedResponse(response, callback);
                }
            }

            @Override
            public void onError(ApiException e) {
                LogUtils.e("请求失败=" + e.getMessage());
                onFailedResponse(e.getMessage(), callback);
            }

            @Override
            public void onCompleted() {

            }
        });
    }


    //Get请求
    public void getRequest(final String url,final XCallBack callback) {
        XHttp.get(url).keepJson(true).execute(new CallBack<String>() {

            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(String response){
                if (!StringUtils.isEmpty(response)) {
                    onSuccessResponse(response, callback);
                    LogUtils.e("服务器返回数据>================================网络请求[" + "],请求日志如下===================================" +
                            "\n\n传给服务器地址:" + url +
                            "\n\n服务器返回的数据>" + response);
                }else {
                    LogUtils.e("服务器返回数据>================================网络请求[" + "],请求日志如下===================================" +
                            "\n\n传给服务器地址:" + url +
                            "\n\n服务器返回的数据>" + response);
                    onFailedResponse(response, callback);
                }
            }

            @Override
            public void onError(ApiException e) {
                LogUtils.e("请求失败=" + e.getMessage());
                onFailedResponse(e.toString(), callback);
            }

            @Override
            public void onCompleted() {}
        });

    }


    private void onSuccessResponse(final String result, final XCallBack callBack) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (callBack != null) {
                    try {
                        callBack.onResponse(result);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private void onFailedResponse(final String result, final XCallBack callBack) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (callBack != null) {
                    callBack.failedRequest(result);
                }
            }
        });
    }


    public interface XCallBack {
        void onResponse(String result) throws JSONException;
        void failedRequest(String result);
    }
}
